package org.leaf.green.b2b

import org.leaf.green.admin.RecordType

import org.springframework.transaction.annotation.*

import org.codehaus.groovy.grails.web.metaclass.BindDynamicMethod

class PickplanService {

    static transactional = true

    //record type
    @Transactional(readOnly = true)
    def recordType() {
        log.info("recordType")
        def recordType_pickplan = RecordType.withCriteria(uniqueResult:true){
            projections{
                property('id')
            }
            eq("domain", "purchase")
            eq("serialNumber", "2")
        }
        log.info("recordType_pickplan=${recordType_pickplan}")
        return recordType_pickplan
    }
    

    @Transactional(readOnly = true)
    def list(Object params) {
        log.info("list_purchase")
        def recordType_pickplan = this.recordType()       
        def pickplanInstanceList = Purchase.withCriteria{
            eq("recordType.id", recordType_pickplan)
            if(params?.max) maxResults(params.int('max'))
			if(params?.offset) firstResult(params.int('offset'))
			if(params?.sort && params?.order) order(params?.sort, params?.order)
            order("id", "asc")
        }

        return pickplanInstanceList
    }

    @Transactional(readOnly = true)
    def count() {
        log.info("count_pickplan")
        def recordType_pickplan = this.recordType()
        def pickplanInstanceCount =  Purchase.withCriteria{
            count("id")
            eq("recordType.id", recordType_pickplan)
       }
        return pickplanInstanceCount
    }


    //init purchase
    def init(Object params){
        //new
        def pickplanInstance = new Purchase()
        //set record type
        BindDynamicMethod mybind = new BindDynamicMethod()
        def mymap = ['recordType.id' : this.recordType()]
        def myargs =  [pickplanInstance, mymap]
        mybind.invoke(pickplanInstance, 'bind', (Object[]) myargs)
        //add details
        def begin_serialNumber = 0
        Product.listOrderBySerialNumber().each{ product ->
            begin_serialNumber += 1
            pickplanInstance.addToDetails(
                new PurchaseDetail(
                      serialNumber : String.format('%03d', begin_serialNumber)
                    , product : product
                    , dealer : null
                    , quantity : 0
                    , price : 0
                    , amount : 0
                    , unit : '斤'
                )
            )
        }
        //set serialnumber
        pickplanInstance.serialNumber = "${new Date().format('yyyyMMdd')}000"
        return pickplanInstance
    }
}
